﻿using datatablegenerator.Common;
using datatablegenerator.DB;
using datatablegenerator.Entity;
using datatablegenerator.Enums;
using datatablegenerator.Factory.DBFactory;
using MySqlX.XDevAPI.Common;
using Org.BouncyCastle.Crypto.Prng;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using Color = System.Windows.Media.Color;

namespace datatablegenerator
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly List<DatatableDTO> DTO;
        /// <summary>
        /// 连接状态
        /// </summary>
        private bool State = false;

        private DbConnection Connection;

        List<DatatableDTO> datatableList = new List<DatatableDTO>();

        public MainWindow()
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen;// 窗体居中
            InitializeComponent();
            #region 表格设计器相关
            DTO = new List<DatatableDTO>();
            DTO.Add(new DatatableDTO { Name = "名称", Type = "", Required = true, Default = "", Remacks = "" });
            this.DatatableGrid.ItemsSource = DTO;
            #endregion

            this.ConnTxt.Text = ConfigurationManager.AppSettings["MySQL"];
        }


        #region 连接数据库
        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            string connTxt = this.ConnTxt.Text.Trim();  //连接字符串

            DBType dbType = DBType.MySql;
            if (this.sqlserver.IsChecked.Value)
            {
                dbType = DBType.SqlServer;
            }

            if (!string.IsNullOrEmpty(connTxt))
            {
                try
                {
                    var dbContext = DBProviderFactoey.CreateDbContext(dbType);

                    var result = dbContext.ConnectionDb(connTxt);
                    if (result.Item1)
                    {
                        MessageBox.Show("连接成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                        State = true;
                        Connection = dbContext.conn;
                        this.StateTxt.Content = "已连接";
                        this.StateTxt.Foreground = new SolidColorBrush(Color.FromRgb(0, 205, 102));
                    }
                    else
                    {
                        MessageBox.Show("连接失败！", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                        State = false;
                        this.StateTxt.Content = "未连接";
                        this.StateTxt.Foreground = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                    }
                }
                catch (Exception ex)
                {
                    State = false;
                    Connection.Close();
                    MessageBox.Show($"{ex.Message}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (State)
            {
                Connection.Close();
            }
        }


        #endregion

        #region 表格解析

        //添加行
        private void Add_Click(object sender, RoutedEventArgs e)
        {

        }

        //删除行
        private void Del_Click(object sender, RoutedEventArgs e)
        {

        }

        private void datatableCombox_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            com();
        }
        private void datatableCombox_KeyUp(object sender, KeyEventArgs e)
        {
            List<string> mylist = new List<string>();
            ComboBox comboBoxinfo = com();

            mylist = DataTypeHelper.ListDataType().FindAll(delegate (string s) { return s.Contains(comboBoxinfo.Text.Trim()); });
            comboBoxinfo.ItemsSource = mylist;
            comboBoxinfo.IsDropDownOpen = true;
        }

        private ComboBox com()
        {
            int index = this.DatatableGrid.CurrentCell.Column.DisplayIndex;
            DataGridTemplateColumn templeColumn = this.DatatableGrid.Columns[index] as DataGridTemplateColumn;
            // if (templeColumn == null) return;

            object item = this.DatatableGrid.CurrentCell.Item;
            FrameworkElement element = templeColumn.GetCellContent(item);
            ComboBox com = (ComboBox)templeColumn.CellTemplate.FindName("datatableCombox", element);
            com.ItemsSource = DataTypeHelper.ListDataType();
            return com;
        }


        #endregion

        #region  Execl模板解析

        //解析文本
        private void Analysis_Click(object sender, RoutedEventArgs e)
        {
            TextRange tr = new TextRange(this.Document.ContentStart, this.Document.ContentEnd);

            string str = tr.Text;
            string[] strArr = str.Split("\r\n").ToArray();

            if (strArr != null)
            {
                //表头信息
                string[] tempArr = strArr[0].Split("\t").Where(r => r != "").ToArray();
                foreach (var item in tempArr)
                {
                    //TODO:待优化                  
                    if (item == "字段名称" || item == "数据类型" || item == "必填" || item == "默认值" || item == "约束" || item == "字段说明")
                    {
                    }
                    else
                    {
                        MessageBox.Show("表头信息有误！");
                        return;
                    }
                }
            }

            foreach (var item in strArr.Skip(1))
            {
                DatatableDTO datatableDto = new DatatableDTO();
                string[] tempStrArr = item.Split("\t").ToArray();

                if (tempStrArr.Length < datatableDto.GetType().GetProperties().Count())
                {
                    break;
                }
                //TODO:待优化
                for (int i = 0; i < tempStrArr.Length; i++)
                {
                    switch (i)
                    {
                        case 0:
                            datatableDto.Name = tempStrArr[i];
                            break;
                        case 1:
                            datatableDto.Type = tempStrArr[i];
                            break;
                        case 2:
                            datatableDto.Required = tempStrArr[i] == "*" ? true : false;
                            break;
                        case 3:
                            datatableDto.Default = tempStrArr[i];
                            break;
                        case 4:
                            datatableDto.Constraint = tempStrArr[i];
                            break;
                        case 5:
                            datatableDto.Remacks = tempStrArr[i];
                            break;
                        default:
                            break;
                    }
                }
                datatableList.Add(datatableDto);
            }

            this.TableDataGrid.ItemsSource = datatableList;
        }

        //清除
        private void Clear_Click(object sender, RoutedEventArgs e)
        {
            ClearData();
        }

        /// <summary>
        /// 清除文本与列表信息
        /// </summary>
        public void ClearData()
        {
            this.TableTxt.Clear();
            //清空RichTextBox
            TextRange tr = new TextRange(this.Document.ContentStart, this.Document.ContentEnd);
            tr.Text = String.Empty;

            //清空列表
            this.TableDataGrid.ItemsSource = null;
            datatableList = new List<DatatableDTO>();
        }

        //确定生成
        private void Commit_Click(object sender, RoutedEventArgs e)
        {
            if (State)
            {
                //表名
                string tableName = this.TableTxt.Text.Trim();

                if (string.IsNullOrWhiteSpace(tableName))
                {
                    MessageBox.Show($"请先输入表名！", "提示", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }

                if (IsTableExist(tableName))
                {
                    MessageBox.Show($"该数据表:{tableName}已存在！", "提示", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }

                string sql = CreateDataTableSQL(tableName, datatableList);

                CreateDataTable(sql, tableName, datatableList);
                MessageBox.Show("创建成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("请先连接数据库！", "提示", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        /// <summary>
        /// 判断数据表是否存在
        /// </summary>
        /// <param name="table"></param>
        /// <returns>true:存在；false:不存在</returns>
        private bool IsTableExist(string table)
        {
            try
            {
                DBType dbType = DBType.MySql;
                if (this.sqlserver.IsChecked.Value)
                {
                    dbType = DBType.SqlServer;
                }
                var provider = DBProviderFactoey.CreateDbContext(dbType);

                var result = provider.IsTableExist(table);
                if (!result.Item1)
                {
                    MessageBox.Show($"{result.Item2}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{ex.Message}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            return false;
        }

        /// <summary>
        /// 创建数据表SQL
        /// </summary>
        /// <param name="dt">要创建的数据表</param>
        /// <param name="dto">数据表中的字段及其数据类型</param>
        /// <returns> 创建表SQL脚本 </returns>
        private string CreateDataTableSQL(string dt, List<DatatableDTO> dto)
        {
            try
            {
                DBType dbType = DBType.MySql;
                if (this.sqlserver.IsChecked.Value)
                {
                    dbType = DBType.SqlServer;
                }
                var provider = DBProviderFactoey.CreateDbContext(dbType);

                var result = provider.CreateDataTableSQL(dt, dto);
                if (!result.Item1)
                {
                    MessageBox.Show(result.Item2, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                    return result.Item2;
                }
                return result.Item2;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                return string.Empty;
            }
        }


        /// <summary>
        /// 创建数据表
        /// </summary>
        /// <param name="sql">sql脚本</param>
        /// <param name="dt">表名</param>
        /// <param name="dto">字段信息</param>
        private void CreateDataTable(string sql, string dt, List<DatatableDTO> dto)
        {
            try
            {

                DBType dbType = DBType.MySql;
                if (this.sqlserver.IsChecked.Value)
                {
                    dbType = DBType.SqlServer;
                }
                var provider = DBProviderFactoey.CreateDbContext(dbType);

                var result = provider.CreateDataTable(sql, dt, dto);
                if (!result.Item1)
                {
                    MessageBox.Show(result.Item2, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                ClearData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }


        /// <summary>
        /// 生成SQL 脚本
        /// </summary>
        /// <param name="dt">表名/param>
        /// <param name="sql">SQL 脚本</param>
        private void GenerateSqlScript(string dt, string sql)
        {
            //TODO:待优化           
            string path = "../script";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            File.WriteAllText(path + $"/{dt}_" + DateTime.Now.ToString("yyyy-MM-dd") + "_" + DateTime.Now.ToString("HH-mm-ss") + ".txt", sql);
        }

        #endregion


    }
}
